﻿using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;
    SqlParameter param;
    SqlDataAdapter da;
    DataSet ds;
    SqlCommandBuilder cb;
    DataView dv;
    DataTable dt;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            initialconnect();
            initialADOObject();
            initialform();
            LoadCategoriesDisconnect();
            Session["isSelect"] = false;
        }
        bool tmp = (bool)Session["isSelect"];
        if (tmp)
        {
            btnDelete.Enabled = true;
            btnUpdate.Enabled = true;
            btnAdd.Enabled = false;
        }
        else
        {
            btnDelete.Enabled = false;
            btnUpdate.Enabled = false;
            btnAdd.Enabled = true;
        }
    }

    #region Code
    void initialconnect()
    {
        try
        {
            con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        }
        catch (Exception)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Connect To Server Fail');", true);
        }
    }
    void initialADOObject()
    {
        cmd = new SqlCommand();
        initialconnect();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SELECT * FROM Production.Categories";
        da = new SqlDataAdapter(cmd);
        cb = new SqlCommandBuilder(da);
        ds = new DataSet();
        da.FillSchema(ds, SchemaType.Mapped);
        da.Fill(ds, "Production.Categories");
    }
    void LoadCategoriesDisconnect()
    {
        try
        {
            dt = new DataTable("Production.Categories");
            dt = ds.Tables["Production.Categories"];
            dv = new DataView(dt);
            gvCategories.AutoGenerateSelectButton = true;
            gvCategories.AllowPaging = true;
            gvCategories.PageSize = 10;
            gvCategories.DataSource = dt;
            gvCategories.DataBind();
        }
        catch (Exception)
        {
            Response.Write("<script>alert('" + "Load Data Fail !" + "')</script>");
        }
    }
    void initialform()
    {
        try
        {
            if (IsPostBack)
            {
                btnUpdate.Enabled = false;
                btnDelete.Enabled = false;
                btnAdd.Enabled = true;
            }
            txtCategoryID.Enabled = false;
            txtCategoryID.Text = "";
            txtCategoryName.Text = "";
            txtDescription.Text = "";
            txtSearchName.Text = "";
        }
        catch (Exception)
        {
            Response.Write("<script>alert('" + "Fails Page! F5 to Reload" + "')</script>");
        }

    }
    void AddCategories()
    {
        try
        {
            initialconnect();
            con.Open();
            cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "sp_Categories_Insert";
            param = new SqlParameter("@categoryname", SqlDbType.NVarChar);
            param.Size = 15;
            param.Value = txtCategoryName.Text;
            cmd.Parameters.Add(param);

            param = new SqlParameter("@description", SqlDbType.NVarChar);
            param.Size = 200;
            param.Value = txtDescription.Text;
            cmd.Parameters.Add(param);

            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
            initialADOObject();
            LoadCategoriesDisconnect();
        }
    }
    void DeleteCategories()
    {
        try
        {
            initialconnect();
            con.Open();
            cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "sp_Categories_Delete";
            param = new SqlParameter("@categoryid", SqlDbType.Int);
            param.Value = txtCategoryID.Text;
            cmd.Parameters.Add(param);
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        finally
        {
            con.Close();
            initialADOObject();
            LoadCategoriesDisconnect();
        }
    }
    void UpdateCategories()
    {
        try
        {
            initialconnect();
            con.Open();
            cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "sp_Categoris_Update";
            param = new SqlParameter("@categoryid", SqlDbType.Int);
            param.Value = txtCategoryID.Text;
            cmd.Parameters.Add(param);

            param = new SqlParameter("@categoryname", SqlDbType.NVarChar);
            param.Size = 40;
            param.Value = txtCategoryName.Text;
            cmd.Parameters.Add(param);

            param = new SqlParameter("@description", SqlDbType.NVarChar);
            param.Size = 30;
            param.Value = txtDescription.Text;
            cmd.Parameters.Add(param);

            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
            initialADOObject();
            LoadCategoriesDisconnect();
        }
    }
    void SearchCategoryName()
    {
        try
        {
            initialconnect();
            initialADOObject();
            LoadCategoriesDisconnect();
            dv = new DataView(dt);
            dv.RowFilter = string.Format("categoryname LIKE'%{0}%'", txtSearchName.Text);
            gvCategories.DataSource = dv;
            gvCategories.DataBind();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    #endregion

    #region Event
    protected void gvCategories_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (gvCategories.Rows.Count > 0)
        {
            try
            {
                if (IsPostBack)
                {
                    btnAdd.Enabled = false;
                    btnDelete.Enabled = true;
                    btnUpdate.Enabled = true;
                }
                GridViewRow r = gvCategories.SelectedRow;
                txtCategoryID.Text = r.Cells[1].Text.ToString();
                txtCategoryName.Text = Server.HtmlDecode(r.Cells[2].Text.ToString());
                txtDescription.Text = Server.HtmlDecode(r.Cells[3].Text.ToString());
                Session["isSelected"] = true;
            }
            catch (Exception)
            {
                Response.Write("<script>alert('" + "Fails Page! F5 to Reload" + "')</script>");
            }
        }
    }
    protected void gvCategories_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            if (!(bool)Session["isSearch"])
            {
                gvCategories.PageIndex = e.NewPageIndex;
                LoadCategoriesDisconnect();
            }
            else
            {
                gvCategories.PageIndex = e.NewPageIndex;
                btnSearch_Click(sender, e);
            }
        }
        catch (Exception)
        {
            Response.Write("<script>alert('" + "Fails Page! F5 to Reload" + "')</script>");
        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        bool check = true;
        try
        {
            AddCategories();
        }
        catch
        {
            check = false;
            Response.Write("<script>alert('" + "Add Fail!" + "')</script>");
        }
        finally
        {
            initialform();
        }
        if (check)
        {
            Response.Write("<script>alert('" + "Add Successfull!" + "')</script>");
            LoadCategoriesDisconnect();
        }
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        bool check = true;
        if (gvCategories.Rows.Count > 0)
        {
            try
            {
                UpdateCategories();
                initialform();
            }
            catch (Exception)
            {
                check = false;
                Response.Write("<script>alert('" + "Update Fail!" + "')</script>");
            }
            finally
            {
                initialform();
            }
            if (check)
            {
                Response.Write("<script>alert('" + "Update Successfull !" + "')</script>");
                LoadCategoriesDisconnect();
            }
        }
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        bool check = true;
        if (gvCategories.Rows.Count > 0)
        {
            try
            {
                DeleteCategories();
            }
            catch (Exception)
            {
                check = false;
                Response.Write("<script>alert('" + "Delete Fail!" + "')</script>");
            }
            finally
            {
                initialform();
            }
            if (check)
            {
                Response.Write("<script>alert('" + "Delete Successfull!" + "')</script>");
                LoadCategoriesDisconnect();
            }
        }
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        initialform();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        bool check = true;
        try
        {
            int tmp = cbSearch.SelectedIndex;
            if (tmp == 0)
                SearchCategoryName();
            Session["isSearch"] = true;
        }
        catch (Exception)
        {
            check = false;
            Response.Write("<script>alert('" + "Search Fail" + "')</script>");
        }
        if (!check || txtSearchName.Text.Trim() == "")
        {
            LoadCategoriesDisconnect();
        }
        else
        {
            btnReload.Enabled = true;
        }
    }
    protected void btnReload_Click(object sender, EventArgs e)
    {
        initialADOObject();
        LoadCategoriesDisconnect();
    }
    #endregion
}
